package wxwoa

import (
	"encoding/json"
	"io/ioutil"

	// "log"
	"strings"
	// "fmt"
	"net/http"

	"github.com/kataras/iris/v12"
)

type WxMenuController struct {
	// https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html

	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context
}

func (c *WxMenuController) PostPostmenu() {
	const token string = "19901108"
	menudata := c.Ctx.FormValue("menu")
	// c.Ctx.Application().Logger().Infof("menudata: %s", menudata)
	if len(menudata) == 0 {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "菜单参数为空"})
	}
	flag, reason := c.postAPI(menudata)
	if flag {
		c.Ctx.JSON(iris.Map{"flag": true, "msg": "设置成功，请访问公众号查看，缓存更新时间2分钟左右。"})
	} else {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "设置失败," + reason})
	}

}

func (c *WxMenuController) postAPI(menudata string) (bool, string) {
	// 01.尝试缓存 access_token
	access_token := WxAccessToken{}.AccessToken(c.Ctx)

	if len(access_token) == 0 {
		c.Ctx.Application().Logger().Infof("创建菜单时，access_token 获取失败")
		return false, "access_token 获取失败"
	}

	url := "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token

	req, err := http.NewRequest("POST", url, strings.NewReader(menudata))
	if err != nil {
		c.Ctx.Application().Logger().Infof("创建菜单时，新建请求失败" + err.Error())
		return false, err.Error()
	}

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		c.Ctx.Application().Logger().Infof("创建菜单时，发送请求失败:" + err.Error())
		return false, err.Error()
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	content := string(body)
	/*
		正确时的返回JSON数据包如下：
		{"errcode":0,"errmsg":"ok"}
		错误时的返回JSON数据包如下（示例为无效菜单名长度）：
		{"errcode":40018,"errmsg":"invalid button name size"}
	*/

	var jsonmap map[string]interface{}
	json.Unmarshal([]byte(content), &jsonmap)

	if errmsg, ok := jsonmap["errmsg"]; ok {
		if errmsg != nil {
			str_ok := errmsg.(string)
			if str_ok == "ok" {
				return true, "ok"
			}

			c.Ctx.Application().Logger().Errorf("创建菜单时，创建失败：%s", content)
			return false, content
		}
	}

	c.Ctx.Application().Logger().Errorf("创建菜单时，微信官方接口返回非预定格式数据: %s", content)
	return false, content
}
